package myJs.help

import myJs.MainCp
import myJs.api.Api
import myJs.cps._
import myJs.myPkg.ReactRouterDOM
import myJs.myPkg.bootstrap.jquery.{AffixOptions, Offset, ScrollspyOptions}
import myJs.myPkg.jquery.$
import org.scalajs.dom.document
import slinky.core.annotations.react
import slinky.core.facade.Hooks._
import slinky.core.{FunctionalComponent, TagElement}
import slinky.web.SyntheticMouseEvent
import slinky.web.html._
import typings.csstype.csstypeStrings
//import myJs.myPkg.i18n.ReactI18next
import myJs.Implicits._

/**
 * Created by yz on 21/1/2022
 */
@react object Cp {

  case class Props(showLoading: Boolean = true)

  val curPage = Help

  val component = FunctionalComponent[Props] { props =>

    object FTool {

      def scrollExec(anchorName: String) = {
        document.getElementById(anchorName).scrollIntoView()
      }

      def scrollToAnchor(anchorName: String) = (e: SyntheticMouseEvent[TagElement#RefType]) => {
        e.preventDefault()
        scrollExec(anchorName)
      }

    }

    useEffect(() => {
      $("body").scrollspy(ScrollspyOptions(target = "#myScrollspy", offset = 1))
      $("#myNav").affix(AffixOptions(offset = Offset(top = 50)))
    }, List()
    )

    val liWidth = 280

    MainCp(title = curPage.titleStr)(

      div(className := "panel panel-default",
        div(className := "panel-heading",
          h3(className := "panel-title",
            s"${curPage.titleStr}"
          )
        ),
        div(className := "panel-body",

          div(style := Style(display = csstypeStrings.flex, maxWidth = 1108),
            div(style := Style(flex = 25, width = "25%"),
              div(id := "myScrollspy",
                div(className := "bs-docs-sidebar affix-top", role := "complementary",
                  ul(style := Style(width = liWidth), className := "nav bs-docs-sidenav", id := "myNav",
                    li(style := Style(width = liWidth), className := "",
                      a(href := s"#1", "1. Overview of GepLiver", onClick := FTool.scrollToAnchor("1"))
                    ),
                    li(style := Style(width = liWidth), className := "",
                      a(href := "#2", "2. Browse Section", onClick := FTool.scrollToAnchor("2"))
                    ),
                    li(style := Style(width = liWidth), className := "",
                      a(href := "#3", "3. Search Section ", onClick := FTool.scrollToAnchor("3"))
                    ),
                    li(style := Style(width = liWidth), className := "",
                      a(href := "#4", "4. Gene Detail ", onClick := FTool.scrollToAnchor("4"))
                    ),
                    li(style := Style(width = 330), className := "",
                      a(href := "#41", onClick := FTool.scrollToAnchor("41"),
                        span(style := Style(marginLeft = 20), "4.1. Human Tissue Page"),
                      )
                    ),
                    li(style := Style(width = 330), className := "",
                      a(href := "#42", onClick := FTool.scrollToAnchor("42"),
                        span(style := Style(marginLeft = 20), " 4.2. Mouse Tissue Page"),
                      )
                    ),
                    li(style := Style(width = 330), className := "",
                      a(href := "#43", onClick := FTool.scrollToAnchor("43"),
                        span(style := Style(marginLeft = 20), "4.3. Human Single Cell Page"),
                      )
                    ),
                    li(style := Style(width = 330), className := "",
                      a(href := "#44", onClick := FTool.scrollToAnchor("44"),
                        span(style := Style(marginLeft = 20), "4.4. Human Cell Line Page"),
                      )
                    ),
                    li(style := Style(width = liWidth), className := "",
                      a(href := "#5", "5. Single Cell Section ", onClick := FTool.scrollToAnchor("5"))
                    ),
                    li(style := Style(width = liWidth), className := "",
                      a(href := "#6", "6. Analysis Section", onClick := FTool.scrollToAnchor("6"))
                    ),
                    li(style := Style(width = 330), className := "",
                      a(href := "#61", onClick := FTool.scrollToAnchor("61"),
                        span(style := Style(marginLeft = 20), "6.1. Dependence Module"),
                      )
                    ),
                    li(style := Style(width = 330), className := "",
                      a(href := "#62", onClick := FTool.scrollToAnchor("62"),
                        span(style := Style(marginLeft = 20), " 6.2. Survival Module"),
                      )
                    ),
                    li(style := Style(width = 330), className := "",
                      a(href := "#63", onClick := FTool.scrollToAnchor("63"),
                        span(style := Style(marginLeft = 20), " 6.3. Comparison Module"),
                      )
                    ),
                    li(style := Style(width = liWidth), className := "",
                      a(href := "#7", "7. Statistical Analysis", onClick := FTool.scrollToAnchor("7"))
                    ),
                    li(style := Style(width = 330), className := "",
                      a(href := "#71", onClick := FTool.scrollToAnchor("71"),
                        span(style := Style(marginLeft = 20), "7.1. RNA-seq Processing"),
                      )
                    ),
                    li(style := Style(width = 330), className := "",
                      a(href := "#72", onClick := FTool.scrollToAnchor("72"),
                        div(style := Style(marginLeft = 20, display = csstypeStrings.flex), "7.2.",
                          div("Single Cell RNA-seq Processing")
                        ),
                      )
                    ),
                  )
                ),
              )
            ),
            div(style := Style(flex = 75, paddingLeft = 15,
              position = csstypeStrings.relative, paddingRight = 15), id := "scrollContent",
              h4(style := STool.title, "1. Overview of GepLiver", id := "1"),
              p(style := STool.paragraph,
                "GepLiver database comprehensively collected RNA sequencing data of 2566 human bulk tissue, 492 mouse liver samples, 27 human liver cell lines and 406,088 single cells in total from large public repositories and projects including GEO, ArrayExpress, TCGA, GTEx and CCLE. These samples covered the entire range of liver developmental stages and biological conditions, such as normal liver of all ages, hepatitis and cirrhosis of various causes, premalignant lesions and prevalent liver tumor types. "
              ),
              p(style := STool.paragraph,
                "Liver single cell datasets are assembled and harmonized into an integrated atlas clustering into 49 cell populations and 33 cell types through manual annotation. Particularly focused on cancer, GepLiver also incorporates the survival data of 800 patients with HCC and ICC as well as the cancer dependency score from Depmap project, providing access to readily interrogate correlations between gene expression and potential functions. Furthermore, users can customize filters for phenotypes, models and other metadata, freely select samples and then compare their expression profiles within the “comparison” section."
              ),
              p(style := STool.paragraph,
                "Featuring the extensive coverage of liver states and the integration of bulk and single cell RNA-seq, GepLiver enables users to browse, visualize and compare gene expression across diverse liver phenotypes and models, and supports a further exploration in single-cell resolution or functional dimension. Thus, our database holds great promise to provide improved insight into liver pathophysiology and aid researchers in developing biomarkers and therapeutic targets for prevention, detection and curation of liver diseases."
              ),
              img(style := Style(width = "100%"), src := s"${Api.images}/h_1.png"),
              h4(style := STool.title, "2. Browse Section", id := "2"),
              p(style := STool.paragraph,
                "In the browse section, four web pages are presented for browsing mRNA and lncRNA, circRNA, Cell Type as well as Dataset respectively. On each page, corresponding feature lists and basic information are included in the table, the rows and columns of which could be selectively shown by different filter choices."
              ),
              div(style := Style(fontSize = 13, marginBottom = 10), "Description of columns"),
              ColumnCp(),
              p(style := STool.paragraph,
                "*Column names in the form of “[other phenotypes] + Median/Mean/Freq” mean the same as their Fetal counterpart after substitute for the corresponding phenotype and therefore are not mentioned above."
              ),
              p(style := STool.paragraph,
                "Taking “mRNA and lncRNA” tab as an example, the detailed usage is as follows.",
              ),
              ul(style := STool.ul,
                li(style:=STool.li,
                  "Select to show the list of mRNA and lncRNA genes derived from human and mouse bulk samples."
                ),
                li(style:=STool.li,
                  "Choose to show genes of a specific gene type or species."
                ),
                li(style:=STool.li,
                  "Select the columns to display in the table."
                ),
                li(style:=STool.li,
                  "Quickly search gene symbol or download the table."
                ),
                li(style:=STool.li,
                  "Order genes by the median expression of fetal livers (or any other phenotype)."
                ),
                li(style:=STool.li,
                  "Filter for genes expressed in at least 50% of fetal livers (or any other phenotype)."
                ),
                li(style:=STool.li,
                  "Click the hyperlink to jump to the “Detail” page exhibiting the expression landscape of this gene."
                )
              ),
              img(style := Style(width = "100%"), src := s"${Api.images}/h_2.png"),
              h4(style := STool.title, "3. Search Section", id := "3"),
              p(style := STool.paragraph,
                "On the “mRNA and lncRNA” page, users can search multiple gene symbols separated by comma and then obtain entries with matching genes and their homologous counterparts in human or mouse species. On the “circRNA” page, except for host gene symbols, chromosome locations of target circRNAs can also be entered to return the results."
              ),
              p(style := STool.paragraph,
                "Note: the search box on the top navigation menu only supports mRNA and lncRNA search. "
              ),
              img(style := Style(width = "100%"), src := s"${Api.images}/h_3.png"),
              h4(style := STool.title, "4. Gene Detail", id := "4"),
              p(style := STool.paragraph,
                "For 33,870 human mRNA and lncRNA genes covered by our liver single cell atlas, expression landscape of bulk tissue, single cells and cell lines can be visualized by clicking “Tissue”, “Single Cell” and “Cell line” tabs respectively; for the rest of human mRNA and lncRNA genes, users can explore expression profiles of both tissue and cell lines; And for all of circRNAs and mouse genes, only “Tissue” part is presented."
              ),
              h4(style := STool.subTitle, "4.1. Human Tissue Page", id := "41"),
              p(style := STool.paragraph,
                "The default boxplot on this page selectively shows the TPM values of target gene in samples with all but tumor adjacent phenotype among all of datasets. Below are detailed instructions."
              ),
              ul(style :=STool.ul,
                li(style:=STool.li,
                  "Here users can change parameters and choices to replot the figure. Filters for phenotype and datasets can be used to select samples of interest. Any combinations of 17 liver phenotype and 36 datasets are supported. The button “Log2(TPM+1)” (Log2(CPM+1) for circRNA) can switch the expression value to the log2-transformed one for plotting. Clicking the Reset button can resume the default parameters."
                ),
                li(style:=STool.li,
                  "Users can export the source table of the boxplot and download the figure in the formats of JPEG, PNG, PDF and SVG. "
                ),
                li(style:=STool.li,
                  "Clicking the “Mmu” can link to the detail section of homologous mouse gene. For those genes with several homologous counterparts, we only retain one of them here."
                ),
              ),
              img(style := Style(width = "100%"), src := s"${Api.images}/h_4.png"),
              h4(style := STool.subTitle, "4.2. Mouse Tissue Page", id := "42"),
              p(style := STool.paragraph,
                "The default boxplot on this page is grouped by phenotype and selectively shows the TPM values of target gene in samples with all but control phenotype among all of datasets. Please check the steps as follows."
              ),
              ul(style :=STool.ul,
                li(style:=STool.li,
                  "Here users can change parameters and choices to replot the figure. Filters for phenotype, datasets and models are used to select samples of interest. Any combinations of 12 liver phenotypes, 17 datasets and 38 models are supported. The button “Log2(TPM+1)” (Log2(CPM+1) for circRNA) can log2-transformed the expression value used for box plot. Clicking the Reset button will resume the default parameters."
                ),
                li(style:=STool.li,
                  "Click to change the group scheme of box plot among three alternatives: “Phenotype”, “Model”, and “Model_duration”. "
                ),
                li(style:=STool.li,
                  "Here users can readily export the source table of the box plot and download the chart. "
                ),
                li(style:=STool.li,
                  "Clicking the “Hsa” can link to the detail section of homologous human gene. For those genes with several homologous counterparts, we only retain one of them here."
                ),
              ),
              img(style := Style(width = "100%"), src := s"${Api.images}/h_5.png"),
              h4(style := STool.subTitle, "4.3. Human Single Cell Page", id := "43"),
              p(style := STool.paragraph,
                "Over 400,000 cells derived from 10 high-quality studies of GEO and SRA have been integrated into a liver single cell reference map, with 12 liver phenotypes involved. Following uniformed procedures of quality control, data integration, cell clustering and annotation, we provide 33 cell types for users to explore the gene expression in single-cell level. Detailed description of single cell data processing can be found in Statistical Analysis section. "
              ),
              p(style := STool.paragraph,
                "In the Expression Profile module, UMAP plot allows users to view the distribution of cells expressing target gene against the background of single cell landscape; box plot facilitates direct comparison of expression level among all cell types; and expression statistics part provides the average expression value and percentage of cells expressing target gene in each cluster."
              ),
              p(style := STool.paragraph,
                "For general information about this liver single cell atlas, users can switch to the Single Cell Landscape module. Cell clustering pattern is visualized in UMAP plot colored by cell type whereas the percentage of each cell type is interactively shown in bar plot. Top10 feature genes of each cluster have been listed in cell type table; the expression of these genes has been plotted as feature heatmap with recognized lineage markers labeled. Marker List table contains all marker genes found for every cluster with the criteria of log2FC>0.25 and pct.1>0.25, and only positive features are returned in the list."
              ),
              p(style := STool.paragraph,
                "To be noted, users can select any of 12 phenotypes to explore cells interested instead of all cells by default in the left panel. This change will transform all graphs and tables except for Feature Heatmap and Marker List."
              ),
              div(style := Style(fontSize = 13, marginBottom = 10), "Description of column names"),
              Column1Cp(),
              img(style := Style(width = "100%",marginTop = 5), src := s"${Api.images}/h_6.png"),
              h4(style := STool.subTitle, "4.4. Human Cell Line Page", id := "44"),
              p(style := STool.paragraph,
                "Target gene expression of 27 liver cancer cell lines from CCLE project is plotted as bar chart on this page by default using the expression value of Log2(TPM+1) and ordered by Alphabet."
              ),
              img(style := Style(width = "100%"), src := s"${Api.images}/h_7.png"),
              h4(style := STool.title, "5. Single Cell Section", id := "5"),
              p(style := STool.paragraph,
                "The Single Cell button on the navigation menu links to Single Cell Landscape module of Detail page. Please check the Human Single Cell Page for more contents."
              ),
              h4(style := STool.title, "6. Analysis Section", id := "6"),
              p(style := STool.paragraph,
                "GepLiver has incorporated the Chronos dependency score from Depmap project (",
                a(href := "https://depmap.org/portal/download/all/", target := "_blank", "https://depmap.org/portal/download/all/"),
                ", Public 22Q1) and survival data of 800 patients with HCC or ICC included in our database for further exploration of gene functions in liver cancer. The dependency score is derived from CRISPR gene knockout assay with a lower score indicating that the selected gene is more likely to affect the viability or proliferation of the specific cell line. Genes with scores of 0 means non-essential for the given cell line. Besides, gene comparison between two customized sample groups is also available in this section. With these analysis modules, GepLiver is expected to combine gene expression, functions, and diverse patient metadata and act as a valuable resource for the identification of driver genes and biomarkers. "
              ),
              h4(style := STool.subTitle, "6.1. Dependence Module", id := "61"),
              ul(style :=STool.ul,
                li(style:=STool.li,
                  "Users can input a gene symbol of interest and click the ”Plot” button to obtain a bar plot of gene dependency scores and a scatter plot showing the correlation between dependency scores and corresponding gene expression values."
                ),
                li(style:=STool.li,
                  "Choose the X axis to determine whether to use log2-transformed TPM value for plotting."
                ),
                li(style:=STool.li,
                  "Change the Linear Regression parameter to choose whether to fit linear regression and which method to calculate the correlation coefficient."
                ),
              ),
              img(style := Style(width = "100%"), src := s"${Api.images}/h_8.png"),
              img(style := Style(width = "100%",marginTop = 5), src := s"${Api.images}/h_9.png"),
              h4(style := STool.subTitle, " 6.2. Survival Module", id := "62"),
              p(style := STool.paragraph,
                "Several types of survival data, including Overall Survival (OS), Disease Specific Survival (DSS), Disease Free Survival (DFS) and Progress Free Survival (PFS) are included in GepLiver for users to choose. Both the Log-rank test and the Cox regression analysis are performed for survival analysis. Users can follow the instructions as illustrated below."
              ),
              ul(style := STool.ul,
                li(style:=STool.li,
                  "Input a gene symbol of interest."
                ),
                li(style:=STool.li,
                  "Choose “HCC” or “ICC” tumor type."
                ),
                li(style:=STool.li,
                  "Choose one dataset of interest."
                ),
                li(style:=STool.li,
                  "Choose one survival data type from “OS”, ‘DSS”, “DFS” and “PFS”."
                ),
                li(style:=STool.li,
                  "Choose median or quantile as upper or lower cutoff for two groups or define a percent value between 0 and 100."
                ),
                li(style:=STool.li,
                  "Click the “Plot” button to obtain the survival curve in the right panel."
                ),
              ),
              img(style := Style(width = "100%"), src := s"${Api.images}/h_10.png"),
              h4(style := STool.title, "6.3. Comparison Module", id := "63"),
              p(style := STool.paragraph,
                "Here users can define two group of samples for comparison based on filters for phenotype, dataset and model. The detailed usage is as follows."
              ),
              ul(style :=STool.ul,
                li(style:=STool.li,
                  "Input a gene symbol of interest."
                ),
                li(style:=STool.li,
                  "Choose species of the given gene. Human species is selected by default."
                ),
                li(style:=STool.li,
                  "For human species, group A is defined as HCC samples of all datasets whereas group B consists of normal and ADJ_HCC phenotypes of all datasets. Correspondingly for mouse HCC versus normal and control phenotypes of all models and datasets are separately selected for two groups. Users are allowed to customize combinations of filter options."
                ),
                li(style:=STool.li,
                  "Choose “wilcox.test” or “t.test” for differential test. Symbols indicating significance levels are as follows. ",
                  br(),
                  "ns: p>0.05; *: p <= 0.05; **: p <= 0.01; ***: p <= 0.001; ****: p <= 0.0001"
                ),
                li(style:=STool.li,
                  "Choose whether to use log2-transformed TPM value for plotting."
                ),
              ),
              img(style := Style(width = "100%"), src := s"${Api.images}/h_11.png"),
              h4(style := STool.title, "7. Statistical Analysis", id := "7"),
              h4(style := STool.title, "7.1. RNA-seq Processing", id := "71"),
              p(style := STool.paragraph,
                "Raw reads (Fastq or BAM file) of all bulk tissue and cell lines are retrieved and processed through the standardized pipeline of ASJA (Assembling Splice Junctions Analysis, https://github.com/HuangLab-Fudan/ASJA) and CIRI2 (circRNA Identifier, https://sourceforge.net/projects/ciri/files/CIRI2/). Alignment files are mapped to the GRCh38 or mm39 sequences. Gene and transcript quantification files are annotated to GENCODE V29, or VM28. The overlap of circRNAs identified by ASJA and CIRI2 is then filtered for those expressed at least in 10 tissue samples with a sum of counts over 10 (For mouse species, the cutoff is at least in 3 samples and sum(counts)>3). Read counts are normalized using TPM for mRNA and lncRNA and CPM for circRNA. For log-transformed expression value, we employed a base of 2 and a pseudocount of 1."
              ),
              h4(style := STool.title, "7.2.Single Cell RNA-seq Processing", id := "72"),
              p(style := STool.paragraph,
                "Expression matrices of human single cell RNA-seq are downloaded from public resources and processed through Seurat (version 4.1.0). Quality control procedure is separately employed to each dataset with uniformed criteria. Cells expressed fewer than 300 genes and with a higher mitochondrial gene percent (taking the smaller one of 25% and 5th percentile of normal distribution modeling mitochondrial gene percent) are removed, as are genes expressed in less than 3 cells. Doublets are predicted using DoubletFinder (version 2.0.3) for each sample and removed before downstream analysis."
              ),
              p(style := STool.paragraph,
                "Expression values shown in GepLiver database are the normalized counts by Seurat’s NormalizeData function. Counts for each cell are divided by the total counts for this cell, multiplied by the scale factor of10^4 and then natural-log transformed for normalization. We apply Seurat’s integration algorithm with default parameters to the harmonization of datasets into a reference liver single cell map and then find 49 clusters with 50pcs and resolution of 1.0. Cell clusters are manually annotated based on literature. "
              ),
            )

          )

        )
      )

    )

  }

  object STool {

    val title = Style(marginBottom = 15, fontSize = 15, fontWeight = csstypeStrings.bold,marginTop = 10)

    val subTitle = Style(marginBottom = 15, fontSize = 14, fontWeight = csstypeStrings.bold,marginTop = 10)

    val paragraph = Style(fontSize = 13, textIndent = "2em")

    val li=Style(paddingBottom = 5,fontSize = 13)

    val ul=Style(listStyle = "decimal")

  }

}
